package org.zjt.mock.demo.mock.config;

import com.alibaba.fastjson.JSON;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpInputMessage;
import org.springframework.http.HttpOutputMessage;
import org.springframework.http.MediaType;
import org.springframework.http.converter.AbstractHttpMessageConverter;
import org.springframework.http.converter.HttpMessageNotReadableException;
import org.springframework.http.converter.HttpMessageNotWritableException;
import org.springframework.http.converter.json.AbstractJackson2HttpMessageConverter;
import org.apache.commons.io.IOUtils;
import org.springframework.util.StreamUtils;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.nio.charset.Charset;
import java.time.LocalDateTime;

/**
 * Description:
 *
 * @author juntao.zhang
 * Date: 2018-06-22 下午1:15
 * @see AbstractHttpMessageConverter
 */
@Slf4j
public class CustomizedJackson2HttpMessageConverter extends AbstractHttpMessageConverter<Object> {


    @Override
    protected boolean supports(Class<?> clazz) {
        return LocalDateTime.class.isAssignableFrom(clazz);
    }

    @Override
    protected Object readInternal(Class<?> clazz, HttpInputMessage inputMessage) throws IOException, HttpMessageNotReadableException {
        Charset charset = getContentTypeCharset(inputMessage.getHeaders().getContentType());
        String content = StreamUtils.copyToString(inputMessage.getBody(), charset);
        log.info("content:{}",content);
        Object o = JSON.parseObject(content, clazz);
        return o;
    }

    @Override
    protected void writeInternal(Object o, HttpOutputMessage outputMessage) throws IOException, HttpMessageNotWritableException {
        Charset charset = getContentTypeCharset(outputMessage.getHeaders().getContentType());
        OutputStream out = outputMessage.getBody();
        String text = JSON.toJSONString(o);
        byte[] bytes = text.getBytes(charset);
        out.write(bytes);
    }


    private Charset getContentTypeCharset(MediaType contentType) {
        if (contentType != null && contentType.getCharset() != null) {
            return contentType.getCharset();
        }
        else {
            return getDefaultCharset();
        }
    }
}
